//
//  YZMProvinceListViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/19.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMProvinceListViewController.h"
#import "YZMBankCardService.h"
#import "YZMSeparatorCell.h"
#import "YZMProvince.h"
#import "YZMCity.h"
#import <LinqToObjectiveC/LinqToObjectiveC.h>
#import <CoreLocation/CoreLocation.h>

@interface YZMProvinceListViewController()<UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *provinceList;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UIButton *locationButton;
@property (nonatomic, strong) NSString *locationProvince;
@property (nonatomic, strong) NSString *locationCity;
@property (nonatomic, strong) UILabel *topLabel;

@end

@implementation YZMProvinceListViewController

- (id)init{
    
    self = [super init];
    
    if (self) {
        self.provinceList = [YZMBankCardService sharedService].provinceList;
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"选择省市";
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    
    [self createObjects];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self startLocation];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [_locationManager stopUpdatingHeading];
    _locationManager.delegate = nil;
}

#pragma mark -- UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"BankCardCell";
    YZMSeparatorCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[YZMSeparatorCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        cell.textLabel.textColor = [YZMAppStyle colorForMainTextColor];
        cell.textLabel.font = [YZMAppStyle mediumSizeFont];
    }
    
    YZMProvince *instance = _provinceList[indexPath.row];
    cell.textLabel.text = instance.name;
    YZMIndexCount indexCount;
    
    [cell.contentView insertSubview:cell.textLabel belowSubview:cell.bottomLineView];
    indexCount.index = indexPath.row;
    indexCount.count = self.provinceList.count;
    cell.indexCount = indexCount;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _provinceList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.delegate) {
        
        YZMProvince *p = _provinceList[indexPath.row];
        [YZMHCMInstance pushViewControllerWithName:@"cityList" andParams:@{@"province":p, @"delegate": self.delegate, @"cityList": [[YZMBankCardService sharedService] fetchCityListForProvince:p]}];
    }
}


#pragma mark -- CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [manager requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //得到newLocation
    CLLocation *cloc = [locations lastObject];
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:cloc completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error)
        {
            for (CLPlacemark * placemark in placemarks) {
                
                NSDictionary *test = [placemark addressDictionary];
                
                _locationProvince = [test objectForKey:@"State"];
                _locationCity = [test objectForKey:@"City"];
                
                _locationButton.enabled = YES;
                _topLabel.text = [NSString stringWithFormat:@"%@ %@", _locationProvince, _locationCity];
            }
        }
        [manager stopUpdatingLocation];
    }];
}

- (void)clickForChooseLocation:(UIButton *)sender{
    
    if (!_locationProvince || _locationProvince.length == 0) {
        
        return;
    }
    
    if (self.delegate) {
        
        YZMProvince *instanceProvince;
        YZMCity *instanceCity;
        
        NSArray *array = [self.provinceList linq_where:^BOOL(YZMProvince *p){
            
            return [self.locationProvince isEqualToString:p.name];
        }];
        
        if (array && array.count != 0) {
            
            instanceProvince = array[0];
            
            NSArray *cityArray = [[[YZMBankCardService sharedService] fetchCityListForProvince:instanceProvince] linq_where:^BOOL(YZMCity *c){
                
                return [_locationCity isEqualToString:c.name];
            }];
            
            if (cityArray && cityArray.count == 0) {
                
                instanceCity = cityArray[0];
                
            }else{
                
                instanceCity = [[YZMCity alloc] init];
                instanceCity.name = _locationCity;
            }
            
        }else{
            
            instanceProvince = [[YZMProvince alloc] init];
            instanceProvince.name = _locationProvince;
            
            instanceCity = [[YZMCity alloc] init];
            instanceCity.name = _locationCity;
        }
        
        [self.delegate provinceDidChoose:instanceProvince andCity:instanceCity];
    }
    
    [YZMHCMInstance popViewController:nil animated:YES];
}


#pragma mark -- Private Method

-(void)startLocation{
    
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
    {
        _topLabel.text = @"您关闭了定位功能，将无法收到位置信息，建议您到系统设置中打开定位功能";
        return;
    }
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 10.0f;
    
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        
        [_locationManager requestWhenInUseAuthorization];
    }
    
    [_locationManager startUpdatingLocation];
}

- (void)createObjects{
    
    _locationButton = [UIButton new];
    _locationButton.backgroundColor = [YZMAppStyle colorForMain];
    _locationButton.enabled = NO;
    [_locationButton addTarget:self action:@selector(clickForChooseLocation:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_locationButton];
    [_locationButton mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.left.right.equalTo(self.view);
        maker.height.mas_equalTo(50);
    }];
    
    UIImageView *locaitonIV = [UIImageView new];
    locaitonIV.image = [UIImage imageNamed:@"icon_blue_location"];
    [_locationButton addSubview:locaitonIV];
    [locaitonIV mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.width.height.mas_equalTo(18);
        maker.left.equalTo(_locationButton).offset(15);
        maker.centerY.equalTo(_locationButton);
    }];
    
    _topLabel = [UILabel new];
    _topLabel.text = @"定位中";
    _topLabel.textColor = [YZMAppStyle colorForGrayText];
    _topLabel.font = [YZMAppStyle mediumSizeFont];
    _topLabel.userInteractionEnabled = YES;
    _topLabel.adjustsFontSizeToFitWidth = YES;
    _topLabel.minimumScaleFactor = 0.5f;
    [_locationButton addSubview:_topLabel];
    [_topLabel mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.equalTo(locaitonIV.mas_right).offset(15);
        maker.centerY.equalTo(_locationButton);
        maker.right.equalTo(_locationButton).offset(15);
    }];
    
    UIView *line = [YZMAppStyle splitLine];
    [_locationButton addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(_locationButton);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(self.view);
        maker.top.equalTo(line.mas_bottom);
    }];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    
    UILabel *headerLabel = [UILabel new];
    headerLabel.text = @"全部";
    headerLabel.textColor = [YZMAppStyle colorForGrayText];
    headerLabel.font = [YZMAppStyle mediumSizeFont];
    [view addSubview:headerLabel];
    [headerLabel mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.equalTo(view).mas_equalTo(15);
        maker.bottom.equalTo(view).offset(-10);
    }];
    
    self.tableView.tableHeaderView = view;
}

#pragma mark -- Params Manager

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMProvinceListViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams:(NSDictionary *)params{
    
    self.delegate = params[@"delegate"];
}


@end
